﻿/*************************************************************************************
 *
 * 文 件 名：  Worker
 * 描    述：
 * 
 * 版    本：  V1.0
 * 创 建 者：  YSW
 * 创建时间：  2021-11-03 15:46:06
 * ======================================
 * 历史更新记录
 * 版本：V          修改时间：         修改人：
 * 修改内容：
 * ======================================
*************************************************************************************/

using CommonModel.Util;
using Dm;
using GXRTBTC.PublicClassLibrary.Redis;
using GXRTBTC.PublicClassLibrary.Util;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NewLife.Caching;
using NewLife.Messaging;
using RedisHelp;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Net.WebSockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Dm.net.buffer.ByteArrayBuffer;

namespace Test
{
    /// <summary>
    /// 后台服务
    /// </summary>
    public class Worker : BackgroundService
    {
        #region
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger mLogger;
        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration mConfiguration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="configuration"></param>
        public Worker(ILogger<Worker> logger, IConfiguration configuration)
        {
            this.mLogger = logger;
            this.mConfiguration = configuration;

            //给通用日志赋值
            CommonUtil.mLogger = logger;

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            Init();
        }

        private void Init()
        { 
        
        }

        ////从缓存读取设置
        //private Dictionary<string, string> paramInfo = redis.HashGetAllDict<string>("paramInfo");
        //private int onlineTimeOut = int.Parse(paramInfo.GetValueOrDefault("OnlineTimeOut", "30"));
        //private List<string> tmpPositionIds = redis.StringGet<List<string>>("positionIds");

        ///// <summary>
        ///// 数据处理
        ///// 工位号
        ///// </summary>
        //private void DealDataPosition()
        //{
        //    Thread.Sleep(1000);
        //    TimeSpan ts;
        //    RedisHelper redis = new RedisHelper(redisConnString, mLogger);
        //    IBatch batch = redis.CreateBatch();
        //    Dictionary<string, string> onlineStatus = new Dictionary<string, string>();
        //    while (true)
        //    {
        //        //采集服务启动时，先写一条服务启动时间，本服务判断启动时间一分钟内不做离线判断，避免重启采集服务造成台站上报超时的告警
        //        //本条key存在时间为2分钟，2分钟内不做离线判断
        //        bool isStart = redis.KeyExists("DataReceiveService_start");
        //        //ping任务数量
        //        //int subTaskCount = redis.HashKeys<string>("SubTaskService").Count;
        //        if (!isStart)
        //        {
        //            var sw = Stopwatch.StartNew();

        //            try
        //            {
        //                //工位离线判断
        //                if (positionIds != null && positionIds.Count > 0)
        //                {
        //                    foreach (string positionId in positionIds)
        //                    {
        //                        string onlineKey = "online_" + positionId;
        //                        string online = redis.StringGet(onlineKey) ?? "1";
        //                        if (onlineStatus.ContainsKey(onlineKey))
        //                        {
        //                            onlineStatus[onlineKey] = online;
        //                        }
        //                        else
        //                        {
        //                            onlineStatus.TryAdd(onlineKey, online);
        //                        }

        //                        DateTime dt = redis.StringGet<DateTime>("newest_time_" + positionId);
        //                        ts = DateTime.Now - dt;

        //                        //总秒数超过参数给定的描述，则认为离线
        //                        if (ts.TotalSeconds > onlineTimeOut && !"1".Equals(onlineStatus[onlineKey]))
        //                        {
        //                            onlineStatus[onlineKey] = "1";
        //                            batch.MStringSetAsync(onlineKey, "1");
        //                        }
        //                    }
        //                }
        //            }
        //            catch (Exception e)
        //            {
        //                mLogger.LogError("工位离线判断异常，" + e.Message);
        //            }
        //            finally
        //            {
        //                batch.Execute();
        //            }
        //        }

        //        //间隔尽量少，判断也需要时间，实际单个台站离线判断也许就需要几秒了
        //        Thread.Sleep(500);
        //    }
        //}

        private async void test()
        {

            while (true)
            {
                string inline = Console.ReadLine();
                try
                {
                    GetDataFromSvr("0101");

                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    //Console.WriteLine(e);
                    Console.WriteLine(e);
                }
                finally
                {
                    Thread.Sleep(10);
                }

                if ("exit".Equals(inline))
                {
                    break;
                }
            }
            mLogger.LogInformation("结束");
        }

        private void GetDataFromSvr(string stationId)
        {
            try
            {
                mLogger.LogInformation("数据同步开始 。。。");
                RedisHelper redis = new RedisHelper("10.170.1.207:6379,10.170.1.211:6379,10.170.1.219:6379,10.170.1.223:6379,10.170.1.249:6379,10.170.1.250:6379,password=gxrtbtc,SyncTimeout=20000");
                redis.SetSysCustomKey("");
                //IBatch batch = redis.CreateBatch();

                RedisHelper redis1 = new RedisHelper("111.111.8.242:6379,password=123456,SyncTimeout=20000");
                IBatch batch1 = redis1.CreateBatch();

                //DATA_0101_
                List<RedisKey> dataKeys = redis.GetKeys($"DATA_{stationId}_");
                foreach (var tmp in dataKeys)
                {
                    string key = tmp.ToString();
                    Dictionary<string, string> data =  redis.HashGetAllDict<string>(key);
                    foreach (string dataKey in data.Keys)
                    {
                        batch1.HashSetAsync("svr_" + key, dataKey, data[dataKey]);
                    }
                }
                batch1.Execute();

                dataKeys = redis.GetKeys($"online_{stationId}_");
                foreach (var tmp in dataKeys)
                {
                    string key = tmp.ToString();
                    string val = redis.StringGet(key);
                    batch1.MStringSetAsync("svr_" + key, val);
                }
                batch1.MExecute();
                mLogger.LogInformation("数据同步完成");
            }
            catch (Exception e)
            {
                mLogger.LogError(e.ToString());
            }
        }
        #endregion

        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            mLogger.LogInformation("服务已启动");
            
            new Thread(test).Start();
            return Task.CompletedTask;
        }
    }
}
